﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using JKF.BusinessLayer.BLL;
using JKF.Entities;
using JKF.Entities.Model;
using JKF.Substructure;
using SFWS.XHandler.Core;

namespace JKF.HandlerLayer.SMS
{
    public class SmsModuleHandler : AHttpHandler
    {
        #region Processor
        public override void ProcessRequest()
        {
            try
            {
                this.HandleRequest(Utils.GetActionName);
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                Utils.ToClient(true, ex.Message);
                AppLogger.Log(ex.Message, ex);  //写日志
            }
        }
        #endregion

        #region Manager
        private bllSMS_TEMPLEATE SMSTemplateMgr = new bllSMS_TEMPLEATE();
        private bllSYS_USER SysUserMgr = new bllSYS_USER();
        private bllSMS_TASK SmsTaskMgr = new bllSMS_TASK();
        private bllSMS_SEND_LOG SmsSendLogMgr = new bllSMS_SEND_LOG();
        private bllSMS_ACCOUNT SmsAccountMgr = new bllSMS_ACCOUNT();
        #endregion

        #region Handlers

        #region sms_task

        /// <summary>
        /// 获取待发送短信列表
        /// </summary>
        public void GetSmsTasks()
        {
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            var obj = new PagerList();

            var result = bllSMS_TASK.GetSmsTaskPaging(bllSYS_USER.CurrentUser.USER_KEY.ToString(), pageCurrent, pageSize, ref pageCount, ref rowCount);
            obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                  select new
                                                  {
                                                      TASK_KEY = a.Field<Guid>("TASK_KEY").ToString(),
                                                      RECEIVER = a.Field<string>("RECEIVER"),
                                                      CONTENT = a.Field<string>("CONTENT"),
                                                      PERIOD_TYPE = a.Field<string>("PERIOD_TYPE"),
                                                      PERIOD_TYPE_NAME = GetSmsPeriodTypeName(a.Field<string>("PERIOD_TYPE")),
                                                      STATUS = a.Field<int>("STATUS"),
                                                      STATUS_NAME = GetSmsStatus(a.Field<int>("STATUS")),
                                                      PERIOD_VALUE = a.Field<string>("PERIOD_VALUE")
                                                  }).ToList();
            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;

        }

        /// <summary>
        /// 删除SmsTask
        /// </summary>
        [Exp2Client]
        public void RemoveSmsTask()
        {
            var taskKey = P("taskKey");
            if (!taskKey.IsGuidB()) throw new Exception("待删除项编号不正确.");
            var taskInfo = SmsTaskMgr.GetModel(taskKey.ToGuid());
            if (taskInfo == null) throw new Exception("待删除项不存在.");
            taskInfo.STATUS = 9;
            taskInfo.DATE_UPDATE = DateTime.Now;
            SmsTaskMgr.Update(taskInfo);
            Response.Write(new ResponseInf
            {
                Success = true
            }.ToJson());
        }

        /// <summary>
        /// 开启或者暂停任务
        /// </summary>
        [Exp2Client]
        public void StartOrStopTask()
        {
            var taskKey = P("taskKey");
            var status = P("status");
            if (status != "0" && status != "1") status = "0";
            if (!taskKey.IsGuidB()) throw new Exception("待更改项编号不正确.");
            var taskInfo = SmsTaskMgr.GetModel(taskKey.ToGuid());
            if (taskInfo == null) throw new Exception("待更改项不存在.");
            taskInfo.STATUS = int.Parse(status);
            taskInfo.DATE_UPDATE = DateTime.Now;
            SmsTaskMgr.Update(taskInfo);
            Response.Write(new ResponseInf
            {
                Success = true,
                Data = new
                {
                    TASK_KEY = taskInfo.TASK_KEY.ToString(),
                    RECEIVER = taskInfo.RECEIVER,
                    CONTENT = taskInfo.CONTENT,
                    PERIOD_TYPE = taskInfo.PERIOD_TYPE,
                    PERIOD_TYPE_NAME = GetSmsPeriodTypeName(taskInfo.PERIOD_TYPE),
                    STATUS = taskInfo.STATUS,
                    STATUS_NAME = GetSmsStatus(taskInfo.STATUS.Value)
                }
            }.ToJson());
        }

        /// <summary>
        /// 添加短信任务
        /// </summary>
        [Exp2Client]
        public void SmsTaskAdd()
        {
            var smsJsonObj = JsonSerializer.Deserialize<SmsTaskJsonInfo>(P("taskObj"));
            var taskInfo = GetTaskInfo(smsJsonObj);
            taskInfo.TASK_KEY = DB.HR.GetNewGuid().ToGuid();
            var smsAccMgr = new bllSMS_ACCOUNT();
            var accountInfos = smsAccMgr.GetListArray(string.Format(" shop_code='{0}'", bllSYS_USER.CurrentUser.SHOP_CODE));
            if (accountInfos == null || accountInfos.Count == 0) throw new Exception(string.Format("当前店铺(店铺编码为\"{0}\")尚未开通短信账号.", bllSYS_USER.CurrentUser.SHOP_CODE));
            if (accountInfos[0].NUM_LEFT <= 0) throw new Exception("短信余额不足，请充值.");
            if (string.IsNullOrEmpty(taskInfo.PERIOD_TYPE))
            {
                var smsCount = 0;//将要发送短信站的条数
                var msgLength = taskInfo.CONTENT.Length;
                var mobiles = taskInfo.RECEIVER.Split(',');
                //计算所需条目
                foreach (var mobile in mobiles)
                {
                    smsCount += CalSmsCount(msgLength, mobile);
                }
                if (accountInfos[0].NUM_LEFT < smsCount) throw new Exception(string.Format("剩余的短信条数足，请充值后发送(剩余条目:{0},本次发送需要条目:{1})。", accountInfos[0].NUM_LEFT, smsCount));


                var ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                ip = string.IsNullOrEmpty(ip) ? Request.ServerVariables["REMOTE_ADDR"] : ip;
                var userCreate = bllSYS_USER.CurrentUser.USER_KEY;
                bllCUSTOMER bllcustomer=new bllCUSTOMER();
                foreach (var mobile in mobiles)
                {
                    var customer = bllCUSTOMER.GetCustomerKeyByMobileNo(mobile);
                    Guid key= customer.IsGuidB() ? customer.ToGuid() : Guid.Empty;
                    var cus=bllcustomer.GetModel(key);
                    string  c ;

                    if (cus != null)
                    {
                        c=taskInfo.CONTENT.Replace("{顾客卡号}", cus.CARD_NO).Replace("{姓名}", cus.NAME).Replace("{性别}", cus.SEX == "1" ? "先生" : "女士").Replace("{生日}", cus.BIRTHDAY == null ? "" : Convert.ToDateTime(cus.BIRTHDAY).ToShortDateString());
                    }
                    else
                    {
                        c = taskInfo.CONTENT;
                    }

                    bllSMS_SEND_LOG.SmsSendLogAdd(new SMS_SEND_LOGinfo()
                    {
                        CONSUME_NUM = CalSmsCount(msgLength, mobile),                        
                    
                       // CONTENT = taskInfo.CONTENT,
                        CONTENT = c,
                        MOBILE = mobile,
                        CUSTOMER_KEY = customer.IsGuidB() ? customer.ToGuid() : Guid.Empty,
                        DATE_CREATE = DateTime.Now,
                        DATE_UPDATE = DateTime.Now,
                        ID = DB.HR.GetNewGuid().ToGuid(),
                        STATUS = "0",
                        USER_CREATE = userCreate,
                        IP = ip,
                        SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE
                    });
                }
            }
            else
                SmsTaskMgr.Add(taskInfo);

            accountInfos = smsAccMgr.GetListArray(string.Format(" shop_code='{0}'", bllSYS_USER.CurrentUser.SHOP_CODE));
            var hasAcc = false;
            if ((accountInfos != null && accountInfos.Count > 0))
            {
                hasAcc = true;
                accountInfos[0].SMS_ACCOUNT = "";
                accountInfos[0].SMS_PWD = "";
            }
            Response.Write(new ResponseInf
            {
                Success = true,
                Data = (hasAcc) ? new
                {
                    NUM_SENDED = accountInfos[0].NUM_SENDED,
                    NUM_LEFT = accountInfos[0].NUM_LEFT,
                    SIGNATURE = accountInfos[0].SIGNATURE
                } : null
            }.ToJson());
        }
        #endregion

        #region Sms_Send_log
        /// <summary>
        /// 获得已发送短信
        /// </summary>
        public void GetSmsSended()
        {
            var obj = new PagerList();
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            var schPara = JsonSerializer.Deserialize<SmsSendedOptions>(P("srchOptions"));
            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;
            DateTime dttmp;

            var result = bllSMS_SEND_LOG.GetSmsSendedPaging(DateTime.TryParse(schPara.DateSendFrom, out dttmp) ? dttmp : new DateTime?(),
                DateTime.TryParse(schPara.DateSendTo, out dttmp) ? dttmp : new DateTime?(),
                schPara.SendShop, schPara.SendNow, schPara.SendState, schPara.Field, schPara.FieldValue
                , bllSYS_USER.CurrentUser.USER_KEY.ToString(), pageCurrent, pageSize, ref pageCount, ref rowCount);

            obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                  select new
                                                  {
                                                      CARD_NO = a.Field<string>("CARD_NO"),
                                                      CUSTOMER_NAME = a.Field<string>("CUSTOMER_NAME"),
                                                      MOBILE = a.Field<string>("MOBILE"),
                                                      CONTENT = a.Field<string>("CONTENT"),
                                                      CONSUME_NUM = a.Field<int>("CONSUME_NUM"),
                                                      OPERATOR = a.Field<string>("OPERATOR"),
                                                      DATE_SEND = a.Field<DateTime?>("DATE_SEND").ToShortDateLineFormat(),
                                                      JUST_TIME_NAME = a.Field<string>("JUST_TIME_NAME"),
                                                      STATUS_NAME = a.Field<string>("STATUS_NAME"),
                                                      REASON_FAILURE = a.Field<string>("REASON_FAILURE")
                                                  }).ToList();
            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;
        }

        /// <summary>
        /// 获取给定客户短信记录
        /// </summary>
        public void GetSendLogsByCustomer()
        {
            var customerKey = P("customerKey");
            var resultInfo = new ResponseInf() { Success = true };
            if (customerKey.IsGuidB())
            {
                var data = bllSMS_SEND_LOG.GetSmsByCustomer(customerKey, bllSYS_USER.CurrentUser.USER_KEY.ToString());
                resultInfo.Data = (from a in data.AsEnumerable()
                                   select new
                                       {
                                           CARD_NO = a.Field<string>("CARD_NO"),
                                           CUSTOMER_NAME = a.Field<string>("CUSTOMER_NAME"),
                                           MOBILE = a.Field<string>("MOBILE"),
                                           CONTENT = a.Field<string>("CONTENT"),
                                           OPERATOR = a.Field<string>("OPERATOR"),
                                           DATE_SEND = a.Field<DateTime?>("DATE_SEND").ToShortDateLineFormat(),
                                           STATUS_NAME = a.Field<string>("STATUS_NAME"),
                                           REASON_FAILURE = a.Field<string>("REASON_FAILURE")
                                       }).ToList();
            }
            Response.Write(resultInfo.ToJson());
        }

        #endregion

        #region SmsTemplate
        /// <summary>
        /// 短信模版列表
        /// </summary>
        public void GetSmsTemplateByPage()
        {
            var obj = new PagerList();
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            var schPara = JsonSerializer.Deserialize<SearchOptions>(P("schOptions"));
            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;
            var result = bllSMS_TEMPLEATE.GetSmsTemplatePaging(schPara.TEMPLEATE_NAME, schPara.IS_START, bllSYS_USER.CurrentUser.USER_KEY.ToString(), pageCurrent, pageSize, ref pageCount, ref rowCount);

            obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                  select new
                                                  {
                                                      ID = a.Field<Guid>("ID").ToString(),
                                                      TEMPLEATE_NAME = a.Field<string>("TEMPLEATE_NAME"),
                                                      IS_START = a.Field<string>("STATUS") == "1" ? "启用" : (a.Field<string>("STATUS") == "0" ? "停用" : ""),
                                                      IS_SHARE = a.Field<string>("IS_SHARE"),
                                                      CONTENT = a.Field<string>("CONTENT"),
                                                      SHOP_CODE = a.Field<string>("SHOP_CODE"),
                                                      DATE_CREATE = a.Field<DateTime?>("DATE_CREATE").ToShortDateLineFormat(),
                                                      OPERATOR = a.Field<string>("OPERATOR")
                                                  }).ToList();
            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;
        }

        /// <summary>
        /// 删除短信模版
        /// </summary>
        [Exp2Client]
        public void RemoveSmsTemplate()
        {
            var tmpId = P("id");
            if (!tmpId.IsGuidB()) throw new Exception("短信模版编号格式不正确.");
            var model = SMSTemplateMgr.GetModel(tmpId.ToGuid());
            if (null == model) throw new Exception("待删除短信模版不存在.");
            SMSTemplateMgr.Delete(tmpId.ToGuid());
            Response.Write(new ResponseInf
            {
                Success = true
            }.ToJson());
        }

        /// <summary>
        /// 编辑短信模版
        /// </summary>
        [Exp2Client]
        public void EditSmsTemplate()
        {
            var tmpJson = JsonSerializer.Deserialize<SMSTemplateJson>(P("smsTemplate"));
            var template = GetSmsTemplateInfo(tmpJson);
            if (tmpJson.ID.IsGuidB())
            {//Edit
                var mode = SMSTemplateMgr.GetModel(tmpJson.ID.ToGuid());
                if (mode == null) throw new Exception("待编辑模版不存在.");
                template.ID = tmpJson.ID.ToGuid();
                template.SHOP_CODE = mode.SHOP_CODE;
                template.USER_CREATE = mode.USER_CREATE;
                template.DATE_CREATE = mode.DATE_CREATE;
                template.DATE_UPDATE = DateTime.Now;
                SMSTemplateMgr.Update(template);
            }
            else
            {//Add
                template.ID = DB.HR.GetNewGuid().ToGuid();
                template.DATE_CREATE = DateTime.Now;
                template.DATE_UPDATE = DateTime.Now;
                template.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY;
                template.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE;
                SMSTemplateMgr.Add(template);
            }
            var sysUser = SysUserMgr.GetModel(template.USER_CREATE);
            Response.Write(new ResponseInf
            {
                Success = true,
                Data = new
                {
                    ID = template.ID.ToString(),
                    TEMPLEATE_NAME = template.TEMPLEATE_NAME,
                    IS_START = template.STATUS == "1" ? "启用" : (template.STATUS == "0" ? "停用" : ""),
                    IS_SHARE = template.IS_SHARE,
                    CONTENT = template.CONTENT,
                    SHOP_CODE = template.SHOP_CODE,
                    DATE_CREATE = template.DATE_CREATE.ToShortDateLineFormat(),
                    OPERATOR = (sysUser != null) ? sysUser.REAL_NAME : ""
                }
            }.ToJson());
        }
        #endregion

        #region Remind

        /// <summary>
        /// 顾客纪念日提醒
        /// </summary>
        public void GetMemoDayRemand()
        {
            var dayDiff = P("dayVal");
            int dayVal;
            if (!int.TryParse(dayDiff, out dayVal)) dayVal = 0;
            var obj = new PagerList();
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;
            var result = bllCUSTOMER.GetRemindByRemindTypePaging(dayVal, 0, bllSYS_USER.CurrentUser.USER_KEY, "",
                pageCurrent, pageSize, ref pageCount, ref rowCount);

            obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                  select new
                                                  {
                                                      CUSTOMER_KEY = a.Field<Guid>("CUSTOMER_KEY").ToString(),
                                                      CARD_NO = a.Field<string>("CARD_NO"),
                                                      NAME = a.Field<string>("NAME"),
                                                      MOBILE = a.Field<string>("MOBILE"),
                                                      DATEY = a.Field<string>("IS_LUNAR_CALENDAR") == "1" ? a.Field<DateTime>("DATEVALUE").ToShortDateLineFormat() : "",
                                                      DATEG = a.Field<string>("IS_LUNAR_CALENDAR") == "0" ? a.Field<DateTime>("DATEVALUE").ToShortDateLineFormat() : "",
                                                      ACTDATE = a.Field<string>("IS_LUNAR_CALENDAR") == "0" ? a.Field<DateTime>("DATEVALUE").ToShortDateLineFormat() : "",
                                                      SMS_DATE = a.Field<DateTime?>("SMS_DATE").ToShortDateLineFormat(),
                                                      PHONE_DATE = a.Field<DateTime?>("PHONE_DATE").ToShortDateLineFormat()
                                                  }).ToList();
            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;
        }

        /// <summary>
        /// 顾客体验提醒
        /// </summary>
        public void GetSwingRemand()
        {
            var dayDiff = P("dayVal");
            int dayVal;
            if (!int.TryParse(dayDiff, out dayVal)) dayVal = 0;
            var obj = new PagerList();
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;
            var result = bllCUSTOMER.GetRemindByRemindTypePaging(dayVal, 2, bllSYS_USER.CurrentUser.USER_KEY, "",
                pageCurrent, pageSize, ref pageCount, ref rowCount);

            obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                  select new
                                                  {
                                                      CUSTOMER_KEY = a.Field<Guid>("CUSTOMER_KEY").ToString(),
                                                      CARD_NO = a.Field<string>("CARD_NO"),
                                                      NAME = a.Field<string>("NAME"),
                                                      MOBILE = a.Field<string>("MOBILE"),
                                                      ACTDATE = a.Field<DateTime?>("DATEVALUE").ToShortDateLineFormat(),
                                                      SMS_DATE = a.Field<DateTime?>("SMS_DATE").ToShortDateLineFormat(),
                                                      PHONE_DATE = a.Field<DateTime?>("PHONE_DATE").ToShortDateLineFormat()
                                                  }).ToList();
            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;
        }

        /// <summary>
        /// 滤芯更换提醒
        /// </summary>
        public void GetFilterRemand()
        {
            var dayDiff = P("dayVal");
            int dayVal;
            if (!int.TryParse(dayDiff, out dayVal)) dayVal = 0;
            var obj = new PagerList();
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;
            var result = bllCUSTOMER.GetRemindByRemindTypePaging(dayVal, 1, bllSYS_USER.CurrentUser.USER_KEY, "",
                pageCurrent, pageSize, ref pageCount, ref rowCount);

            obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                  select new
                                                  {
                                                      CUSTOMER_KEY = a.Field<Guid>("CUSTOMER_KEY").ToString(),
                                                      CARD_NO = a.Field<string>("CARD_NO"),
                                                      NAME = a.Field<string>("NAME"),
                                                      MOBILE = a.Field<string>("MOBILE"),
                                                      ACTDATE = a.Field<DateTime?>("DATEVALUE").ToShortDateLineFormat(),
                                                      SMS_DATE = a.Field<DateTime?>("SMS_DATE").ToShortDateLineFormat(),
                                                      PHONE_DATE = a.Field<DateTime?>("PHONE_DATE").ToShortDateLineFormat()
                                                  }).ToList();
            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;
        }

        /// <summary>
        /// 获得耗材更换提醒
        /// </summary>
        public void GetProductRemand()
        {
            var dayDiff = P("dayVal");
            var productName = P("productName").Trim();
            int dayVal;
            if (!int.TryParse(dayDiff, out dayVal)) dayVal = 0;
            var obj = new PagerList();
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;
            var result = bllCUSTOMER.GetRemindByRemindTypePaging(dayVal, 3, bllSYS_USER.CurrentUser.USER_KEY, productName,
                pageCurrent, pageSize, ref pageCount, ref rowCount);

            obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                  select new
                                                  {
                                                      CUSTOMER_KEY = a.Field<Guid>("CUSTOMER_KEY").ToString(),
                                                      CARD_NO = a.Field<string>("CARD_NO"),
                                                      NAME = a.Field<string>("NAME"),
                                                      MOBILE = a.Field<string>("MOBILE"),
                                                      ACTDATE = a.Field<DateTime?>("DATEVALUE").ToShortDateLineFormat(),
                                                      SMS_DATE = a.Field<DateTime?>("SMS_DATE").ToShortDateLineFormat(),
                                                      PHONE_DATE = a.Field<DateTime?>("PHONE_DATE").ToShortDateLineFormat()
                                                  }).ToList();
            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;
        }

        #endregion

        #region SmsAccount
        /// <summary>
        /// 获取短信账户信息
        /// </summary>
        [Exp2Client]
        public void GetSmsAccountInfo()
        {
            var accList = SmsAccountMgr.GetListArray(
                    string.Format(" SHOP_CODE='{0}'",
                    bllSYS_USER.CurrentUser.SHOP_CODE));

            var rslt = new ResponseInf() { Success = true };
            if (accList.Count <= 0)
            {
                rslt.Data = null;
            }
            accList[0].SMS_PWD = "";
            rslt.Data = accList[0];
            Response.Write(rslt.ToJson());
        }
        #endregion

        #region SmsTaskLog
        /// <summary>
        /// 获得短信任务执行日志
        /// </summary>
        [Exp2Client]
        public void GetSmsTaskLog()
        {
            var dts = P("dateStart");
            var dte = P("dateEnd");
            var taskKey = P("taskKey");
            DateTime dtStart, dtEnd;
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            if (!taskKey.IsGuidB()) throw new Exception("短信任务编号格式不正确.");
            var obj = new PagerList();
            ;
            DateTime.TryParse(dte, out  dtEnd);

            var result = bllSMS_TASK.GetSmsTaskLog(taskKey, DateTime.TryParse(dts, out  dtStart) ? dtStart : new DateTime?(), DateTime.TryParse(dts, out  dtStart) ? dtStart : new DateTime?(),
                pageCurrent, pageSize, ref pageCount, ref rowCount);

            obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                  select new
                                                  {
                                                      CONTENT = a.Field<string>("CONTENT"),
                                                      DATA_CREATE = a.Field<DateTime>("DATA_CREATE").ToShortDateLineFormat(),
                                                      SMS_COUNT = a.Field<int>("SMS_COUNT")
                                                  }).ToList();
            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;

        }
        #endregion

        #endregion

        #region Internal Class Helper

        /// <summary>
        /// 从客户端Jsonbuild短信模版
        /// </summary>
        /// <param name="tmpJson"></param>
        /// <returns></returns>
        public SMS_TEMPLEATEinfo GetSmsTemplateInfo(SMSTemplateJson tmpJson)
        {

            if (tmpJson.TEMPLEATE_NAME.Trim().Length == 0) throw new Exception("请填写模版名称.");
            if (tmpJson.TEMPLEATE_NAME.Trim().Length > 50) throw new Exception("模版名称不可超过50个字符.");
            if (tmpJson.CONTENT.Trim().Length == 0) throw new Exception("请填写模版内容.");
            if (tmpJson.CONTENT.Trim().Length > 50) throw new Exception("模版内容不可超过50个字符.");
            var template = new SMS_TEMPLEATEinfo
            {
                TEMPLEATE_NAME = tmpJson.TEMPLEATE_NAME,
                CONTENT = tmpJson.CONTENT,
                IS_SHARE = tmpJson.IS_SHARE,
                STATUS = tmpJson.IS_START
            };
            return template;
        }
        /**/
        /// <summary>
        /// 短信任务类型
        /// </summary>
        /// <param name="period"></param>
        /// <returns></returns>
        public string GetSmsPeriodTypeName(string period)
        {
            switch (period)
            {
                case "0":
                    return "一次性";
                case "1":
                    return "每天";
                case "2":
                    return "每周";
                case "3":
                    return "每月";
                case "4":
                    return "每年";

            }
            return "";
        }

        /// <summary>
        /// 短信任务状态
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public string GetSmsStatus(int status)
        {
            switch (status)
            {
                case 0:
                    return "暂停";
                case 1:
                    return "等待执行";
                case 9:
                    return "已删除";
            }
            return "";
        }

        /// <summary>
        /// 获得短信任务信息
        /// </summary>
        /// <param name="taskJsonInfo"></param>
        /// <returns></returns>
        public SMS_TASKinfo GetTaskInfo(SmsTaskJsonInfo taskJsonInfo)
        {
            var taskInfo = new SMS_TASKinfo();
            taskInfo.CONTENT = taskJsonInfo.Content;
            taskInfo.DATE_CREATE = DateTime.Now;
            taskInfo.DATE_UPDATE = DateTime.Now;
            taskInfo.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY;
            taskInfo.CONDITION_KEY = taskJsonInfo.ConditionKey.IsGuidB() ? taskJsonInfo.ConditionKey.ToGuid() : Guid.Empty;
            taskInfo.IS_MUST = "0";
            taskInfo.PERIOD_TYPE = taskJsonInfo.ByTimeStyle;
            DateTime dttmp;
            int hour, minute, week, day;
            switch (taskJsonInfo.ByTimeStyle)
            {
                case "0":
                    if (!DateTime.TryParse(taskJsonInfo.Date, out dttmp)) throw new Exception("请选择发送日期.");
                    if (!int.TryParse(taskJsonInfo.Hour, out hour)) throw new Exception("请选择小时.");
                    if (!int.TryParse(taskJsonInfo.Minute, out minute)) throw new Exception("请选择分钟.");
                    taskInfo.PERIOD_VALUE = string.Format("{0} {1}:{2}", dttmp.ToShortDateLineFormat(), hour, minute);
                    break;
                case "1":
                    if (!int.TryParse(taskJsonInfo.Hour, out hour)) throw new Exception("请选择小时.");
                    if (!int.TryParse(taskJsonInfo.Minute, out minute)) throw new Exception("请选择分钟.");
                    taskInfo.PERIOD_VALUE = string.Format("{0}:{1}", hour, minute);
                    break;
                case "2":
                    if (string.IsNullOrEmpty(taskJsonInfo.Week)) throw new Exception("请选择周.");
                    if (!int.TryParse(taskJsonInfo.Hour, out hour)) throw new Exception("请选择小时.");
                    if (!int.TryParse(taskJsonInfo.Minute, out minute)) throw new Exception("请选择分钟.");
                    taskInfo.PERIOD_VALUE = string.Format("{0} {1}:{2}", taskJsonInfo.Week, hour, minute);
                    break;
                case "3":
                    if (!int.TryParse(taskJsonInfo.Day, out day)) throw new Exception("请选择日期.");
                    if (!int.TryParse(taskJsonInfo.Hour, out hour)) throw new Exception("请选择小时.");
                    if (!int.TryParse(taskJsonInfo.Minute, out minute)) throw new Exception("请选择分钟.");
                    taskInfo.PERIOD_VALUE = string.Format("{0} {1}:{2}", day, hour, minute);
                    break;
                default:
                    taskInfo.PERIOD_VALUE = "";
                    break;
            }
            taskInfo.RECEIVER = string.Join(",", taskJsonInfo.MobileNums);
            taskInfo.SCOPE = taskJsonInfo.ScopeCondition ? "0" : "1";
            taskInfo.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE;
            taskInfo.STATUS = 1;
            taskInfo.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY;
            return taskInfo;
        }
        #endregion

        #region Class
        /// <summary>
        /// Sms Template Search optoon
        /// </summary>
        public class SearchOptions
        {
            public string IS_START;
            public string TEMPLEATE_NAME;
        }

        /// <summary>
        /// 短信模版
        /// </summary>
        public class SMSTemplateJson
        {
            public string ID;
            public string TEMPLEATE_NAME;
            public string IS_START;
            public string IS_SHARE;
            public string CONTENT;
        }

        /// <summary>
        /// 查询发送记录
        /// </summary>
        public class SmsSendedOptions
        {
            public string DateSendFrom;
            public string DateSendTo;
            public string SendShop;
            public string SendState;
            public string Field;
            public string FieldValue;
            public string SendNow;
        }

        /// <summary>
        /// 添加短信ClientJson
        /// </summary>
        public class SmsTaskJsonInfo
        {
            public bool ScopeCondition;
            public string ConditionKey;
            public string[] MobileNums;
            public string Content;
            public string Date;
            public string Day;
            public string Week;
            public string Hour;
            public string Minute;
            public bool SendNow;
            public string ByTimeStyle;
        }
        #endregion

        #region Validate
        /// <summary>
        /// 计算本次发送短信条目
        /// </summary>
        /// <param name="smsLength"></param>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static int CalSmsCount(int smsLength, string mobile)
        {
            var smsmax = SMSMxWords;
            int ydmax = 0, ltmax = 0, xltmax = 0, ydCount = 0, ltCount = 0, xltCount = 0;
            if (smsmax.Length == 3)
            {
                ydmax = (int.TryParse(smsmax[0], out ydmax)) ? ydmax : 70;
                ltmax = (int.TryParse(smsmax[1], out ltmax)) ? ltmax : 70;
                xltmax = (int.TryParse(smsmax[2], out xltmax)) ? xltmax : 56;
            }
            var ydMobileCount = IsChinaMobile(mobile) ? 1 : 0;
            var ltMobileCount = ydMobileCount != 1 && IsChinaUnion(mobile) ? 1 : 0;
            var xltMobileCount = (ydMobileCount == 0 && ltMobileCount == 0) ? 1 : 0;
            ydCount = smsLength % ydmax;
            ltCount = smsLength % ltmax;
            xltCount = smsLength % xltmax;
            ydCount = ydCount > 0 ? (smsLength + (ydmax - ydCount)) / ydmax : smsLength / ydmax;
            ltCount = ltCount > 0 ? (smsLength + (ltmax - ltCount)) / ltmax : smsLength / ltmax;
            xltCount = xltCount > 0 ? (smsLength + (xltmax - xltCount)) / xltmax : smsLength / xltmax;

            return ydCount * ydMobileCount + ltCount * ltMobileCount + xltCount * xltMobileCount;
        }

        //短信平台支持的手机号码
        private static List<string> allNum = new List<string>("134,135,136,133,137,138,139,150,151,152,153,158,159,157,188,180,130,131,132,155,156,133,153,189,187".Split(','));
        private static List<string> ydNum = new List<string>("134,135,136,137,138,139,150,151,153,152,158,159,157,188,186,187".Split(','));//移动号码
        private static List<string> ltNum = new List<string>("130,131,132,133,155,156,133,153,189,185,180".Split(','));//联通号码
        private static string[] SMSMxWords = new string[] { "70", "70", "56" };
        /// <summary>
        /// 是否为合法的手机号码
        /// </summary>
        /// <param name="mobileNo"></param>
        /// <returns></returns>
        public static bool IsValidMobileNo(string mobileNo)
        {
            return Regex.IsMatch(mobileNo, @"^1[358]\d{9}$", RegexOptions.IgnoreCase) && allNum.Contains(mobileNo.Substring(0, 3));
        }

        /// <summary>
        /// 是否是移动号码
        /// </summary>
        /// <param name="mobileNo"></param>
        /// <returns></returns>
        public static bool IsChinaMobile(string mobileNo)
        {
            return ydNum.Contains(mobileNo.Substring(0, 3));
        }

        /// <summary>
        /// 是否是联通的号码
        /// </summary>
        /// <param name="mobileNo"></param>
        /// <returns></returns>
        public static bool IsChinaUnion(string mobileNo)
        {
            return ltNum.Contains(mobileNo.Substring(0, 3));
        }

        /// <summary>
        /// 是否是小灵通
        /// </summary>
        /// <param name="mobileNo"></param>
        /// <returns></returns>
        public static bool IsXiaoLT(string mobileNo)
        {
            return false;
        }

        /// <summary>
        /// 验证手机号码，将错误的手机号码分离出来,
        /// 并Select Distinct Mobile Numbers
        /// </summary>
        /// <param name="mobilelst"></param>
        /// <param name="invalidNos"></param>
        public static void ValidateMobileNo(ref List<string> mobilelst, ref List<string> invalidNos)
        {
            invalidNos = mobilelst.Where(a => (!IsValidMobileNo(a))).ToList();
            mobilelst = mobilelst.Where(a => (IsValidMobileNo(a))).ToList();
            //Remove Redundance Items
            mobilelst = (new HashSet<string>(mobilelst.ToArray()).ToList());
        }

        /// <summary>
        /// 是否是可被发送的手机号码
        /// </summary>
        /// <param name="mobileNos"></param>
        /// <returns></returns>
        public static bool IsAllowBySys(string mobileNo)
        {
            if (IsValidMobileNo(mobileNo))
            {
                return ((IsChinaMobile(mobileNo)) || IsChinaUnion(mobileNo) || IsXiaoLT(mobileNo));
            }
            return false;
        }
        #endregion
    }
}
